﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NetAcademia.Web.Mvc.ImageRendering;
using System.IO;

namespace MvcApplication6.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";
            return View();
            //return RedirectToRoute(new { controller = "xamltomvc", action = "index" });
        }

        public ActionResult About()
        {
            return View();
        }

        [HttpPost]
        public ActionResult UploadFile()
        {
            SamplesDBDataContext dc = new SamplesDBDataContext();

            Sample s = new Sample();

            int rank;
            if (int.TryParse(Request.Form["Rank"], out rank))
                s.Rank = rank;
            s.Title = Request.Form["Title"];

            HttpPostedFileBase file = Request.Files["Image"];

            if (file.ContentLength > 0)
            {
                s.ContentType = file.ContentType;
                s.Filename = file.FileName;

                using (MemoryStream ms = new MemoryStream())
                {
                    file.InputStream.CopyTo(ms);
                    s.Image = ms.GetBuffer();
                }
            }

            dc.Samples.InsertOnSubmit(s);
            dc.SubmitChanges();
            
            return RedirectToAction("Index");
        }

 

        public FileContentResult DataRendererImage(string id)
        {
            XamlToPng renderer = new XamlToPng();
            var result = renderer.GetPngFromXaml(id, ControllerContext.RequestContext.HttpContext.Request.QueryString, ControllerContext.HttpContext.Server);
            return File(result.Bits, result.ContentType, result.DownloadFileName);
        }
    }
}
